package com.zhudoo.zhilian.util.socket;

import com.zhudoo.zhilian.dao.entity.User;
import com.zhudoo.zhilian.dao.impl.UserDao;
import com.zhudoo.zhilian.util.web.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhudao
 */
@ServerEndpoint(value = "/sendMsg/{token}")
@Component
public class SendSocketMessage {

    private static UserDao userDao;

    @Autowired
    private UserDao autoUserDao;

    @PostConstruct
    public void init() {
        userDao = autoUserDao;
    }

    private static Logger logger = LoggerFactory.getLogger(SendSocketMessage.class);

    private static final Map<Integer, Session> WEBSOCKET_MAP = new HashMap<>(1000);

    /**
     * 创建一个socket会话时调用的方法
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        try {
            User user = userDao.findUserByToken(token);
            WEBSOCKET_MAP.put(user.getId(), session);
            logger.info("新增用户ID:" + user.getId() + ",Socket当前链接数" + WEBSOCKET_MAP.size());
        } catch (BusinessException ex) {
            logger.info("新增用户业务异常:{}", ex.getMessage());
        }
    }

    /**
     * 关闭一个socket会话时调用的方法
     */
    @OnClose
    public void onClose(@PathParam("token") String token) {
        try {
            User user = userDao.findUserByToken(token);
            WEBSOCKET_MAP.remove(user.getId());
            logger.info("关闭用户ID:" + user.getId() + ",Socket当前链接数" + WEBSOCKET_MAP.size());
        } catch (BusinessException ex) {
            logger.info("关闭用户业务异常:{}", ex.getMessage());
        }
    }

    /**
     * 出错
     *
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        logger.warn("socket出现错误:{}", throwable.getMessage());
    }


    /**
     * 发送消息给对方
     *
     * @param userId
     * @param sendText
     */
    public static Boolean sendText(Integer userId, String sendText) {
        if (WEBSOCKET_MAP.containsKey(userId)) {
            try {
                WEBSOCKET_MAP.get(userId).getBasicRemote().sendText(sendText);
            } catch (Exception e) {
                logger.error("socket发送错误", e);
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
}